#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>

// 定义两ucontext_t 来进行上下文切换
ucontext_t context1, expensive_context;

void context1_func(void) {
    printf("context1_func: started\n");
    // 注意：这里没有调用 swapcontext()
    printf("context1_func: finished\n");
    swapcontext(&context1, &expensive_context);
    printf("code will never reached !\n");
}

void make_context1(void) {

    printf("enter make_context1\n");
    if (getcontext(&context1) == -1) {
        perror("getcontext\n");
        return;
    }

    // 设置 context1 的堆栈
    char *stack1 = (char *)malloc(8192);
    if(stack1 == NULL) {
        perror("malloc error\n");
        return;
    }
    context1.uc_link = nullptr; 
    context1.uc_stack.ss_sp = stack1;
    context1.uc_stack.ss_size = sizeof(stack1);
    makecontext(&context1, context1_func, 0);

    printf("leave make_context1\n");
}

int getExpensiveNum() {
    printf("enter getExpensiveNum\n");
    make_context1();
    if (swapcontext(&expensive_context, &context1) == -1) { // 保存 expensive_context 并切换到 context1
        perror("swapcontext\n");
        return 1;
    }
    // 在合适的时机恢复到这里
    printf("leave getExpensiveNum\n");
    return 1;
}

int main(void) {
    int result = getExpensiveNum();
    printf("expensive return is:%d\n", result);
    printf("main: returned\n"); 
    return 0;
}
